package com.boomsecret.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.StandardLockInternalsDriver;
import org.apache.zookeeper.CreateMode;

/**
 * Created by wangjinliang on 2018/8/6.
 * 实现非公平锁
 */
public class NoFairLockDriver extends StandardLockInternalsDriver {
    private static int DEFAULT_LENGTH = 5;

    private int numLength;

    public NoFairLockDriver() {
        this(DEFAULT_LENGTH);
    }

    public NoFairLockDriver(int numLength) {
        this.numLength = numLength;
    }

    public String getRandomSuffix() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numLength; i++) {
            sb.append((int) (Math.random() * 10));
        }
        return sb.toString();
    }

    @Override
    public String createsTheLock(CuratorFramework client, String path, byte[] lockNodeBytes) throws Exception {
        String newPath = path + getRandomSuffix();
        if (lockNodeBytes != null) {
            return client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL).forPath(newPath, lockNodeBytes);
        } else {
            return client.create().creatingParentContainersIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL).forPath(newPath);
        }
    }
}
